/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { data, order as orderApi, security, store } from "@mall/api-services"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import Icon from "../icon"
import OrderItem from "./order-item"
import "./order-list.scss"

interface OrderProps extends RouteComponentProps {
  order: orderApi.Order;
}

interface OrderState {
  storeInfo: store.Store;
}

class OrderComponent extends React.Component<OrderProps, OrderState> {

  public constructor(props: Readonly<OrderProps>) {
    super(props)

    this.state = {
      storeInfo: new store.Store(),
    }

    this.refreshStore = this.refreshStore.bind(this)
  }

  public componentDidMount(): void {
    this.refreshStore()
  }

  public render() {
    const { history, order } = this.props
    const { items } = order
    const { storeInfo } = this.state
    return (
      <div className="order">
        <Flex justifyContent="space-between"
              onClick={() => history.push(`/stores/${storeInfo.id}`)}>
          <Flex className="order-store-title" alignItems="center">
            <span>{storeInfo.name}</span>
            <Icon type="right" size="xxs"/>
          </Flex>
          <span className="order-status-name">{this.renderStatusName()}</span>
        </Flex>
        <Flex direction="column" onClick={() => history.push(`/order-details/${order.id}`)}>
          {_.map(items, item => <OrderItem key={item.id} item={item}/>)}
        </Flex>
      </div>
    )
  }

  private renderStatusName() {
    const { order } = this.props
    const { OrderStatus } = orderApi
    switch (order.status) {
      case OrderStatus.Pending :
      case OrderStatus.AwaitingPayment :
        return "等待买家付款"
      case OrderStatus.AwaitingFulfillment :
        return "等待打包"
      case OrderStatus.AwaitingShipment :
        return "等待揽收"
    }

    return ""
  }

  private refreshStore() {
    const { order } = this.props
    store.StoreServiceV1
      .getStore(order.storeId)
      .then(storeInfo => this.setState({ storeInfo }))
  }
}

const Order = withRouter(OrderComponent)

interface OrderListProps extends RouteComponentProps {

}

interface OrderListState {
  pagedOrders: data.PageList<orderApi.Order>,
  status?: orderApi.OrderStatus,
}

class OrderList extends React.Component<OrderListProps, OrderListState> {

  public constructor(props: Readonly<OrderListProps>) {
    super(props)

    this.state = {
      pagedOrders: data.PageList.empty<orderApi.Order>(),
    }

    this.handleSetStatus = this.handleSetStatus.bind(this)
  }

  public componentDidMount(): void {
    this.refreshOrders()
  }

  public render() {
    const { history } = this.props
    const { pagedOrders, status } = this.state
    const { OrderStatus } = orderApi
    return (
      <div className="order-list">
        <header className="order-list-header">
          <NavBar left={<Icon type="left" onClick={() => history.goBack()}/>}
                  right={<Icon type="search"/>}>我的订单</NavBar>
          <Flex className="order-status-filter-bar" justifyContent="space-evenly">
                        <span className={classNames("order-status", {
                          "active": _.isEmpty(status),
                        })} onClick={() => this.handleSetStatus(undefined)}>全部</span>
            <span className={classNames("order-status", {
              "active": status === OrderStatus.AwaitingPayment,
            })} onClick={() => this.handleSetStatus(OrderStatus.AwaitingPayment)}>待付款</span>
            <span className={classNames("order-status", {
              "active": status === OrderStatus.AwaitingShipment,
            })} onClick={() => this.handleSetStatus(orderApi.OrderStatus.AwaitingShipment)}>待发货</span>
            <span className={classNames("order-status", {
              "active": status === OrderStatus.AwaitingPickup,
            })} onClick={() => this.handleSetStatus(orderApi.OrderStatus.AwaitingPickup)}>待收货</span>
            <span className={classNames("order-status", {
              "active": status === OrderStatus.Completed,
            })} onClick={() => this.handleSetStatus(orderApi.OrderStatus.Completed)}>待评价</span>
          </Flex>
        </header>
        <div className="order-list-content">
          {_.map(pagedOrders.elements, order => <Order key={order.id} order={order}/>)}
        </div>
      </div>
    )
  }

  public handleSetStatus(status?: orderApi.OrderStatus) {
    this.setState({ status }, () => this.refreshOrders())
  }

  public refreshOrders() {
    orderApi.OrderServiceV1.getOrders()
      .customerId(security.SecurityUserHolder.getUserId())
      .statuses(this.queryStatuses() as [])
      .list()
      .then(list => this.setState({ pagedOrders: list }))
  }


  private queryStatuses(): orderApi.OrderStatus[] | undefined {
    const { OrderStatus } = orderApi
    switch (this.state.status) {
      case OrderStatus.AwaitingPayment:
        return [OrderStatus.Pending, OrderStatus.AwaitingPayment]
      case OrderStatus.AwaitingShipment:
        return [OrderStatus.AwaitingFulfillment, OrderStatus.AwaitingShipment]
      case OrderStatus.AwaitingPickup:
        return [OrderStatus.AwaitingPickup]
      case OrderStatus.Completed:
        return [OrderStatus.Completed]
      default :
        return undefined
    }
  }
}

export default withRouter(OrderList)
